import { request } from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //存储商品详情对象
    goodsObj:{} ,
    isCollect:false

  },
  GoodsInfo:{},

  onShow: function () {
    //Onshow函数获取options
    let pages =getCurrentPages();
    let currentpage =pages[pages.length-1]
    const options = currentpage.options;

    const{goods_id} = options;
    this.getGoodsDetail(goods_id)
  },

  // 获取商品详情数据
 async getGoodsDetail(goods_id){
  const res = await request({url:"/goods/detail",data:{goods_id}})
  const goodsObj=res.data.message
  this.GoodsInfo = goodsObj

  //1 获取缓存中的商品收藏的数组
    let collect = wx.getStorageSync("collect") || [];
    
    // 2 判断当前商品是否被收藏
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id);
 //给商品详情对象赋值
  this.setData({
    goodsObj:{
      goods_name:goodsObj.goods_name,
      goods_price:goodsObj.goods_price,
      goods_introduce:goodsObj.goods_introduce,
      pics:goodsObj.pics
    },
    isCollect

  })

  },

  // 点击图片预览
  handleprevewImage(e){
    const urls =this.GoodsInfo.pics.map(v=>v.pics_mid);
    const current =e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    });
      
    
  },
  // 点击加入购物车
  handleCartAdd(){
    //1.判断缓存里是否有该商品
    let cart  =wx.getStorageSync('cart')||[];
    let index = cart.findIndex(v => v.goods_id===this.GoodsInfo.goods_id)
      if(index===-1){
        // 如果缓存里没有，则添加
        this.GoodsInfo.num=1;
        this.GoodsInfo.check=true;
        cart.push(this.GoodsInfo)
      }else{
        // 如果有 数量加一
        cart[index].num++
      }
    // 替换旧的缓存
    wx.setStorageSync("cart",cart)
    //弹出添加成功提示
    wx.showToast({
      title: '加入购物车成功',
      icon: 'succeed',
      mask: true,
    });
  },
   // 点击 商品收藏图标
   handleCollect(){
    let isCollect=false;
    // 1 获取缓存中的商品收藏数组
    let collect=wx.getStorageSync("collect")||[];
    // 2 判断该商品是否被收藏过
    let index=collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    // 3 当index！=-1表示 已经收藏过 
    if(index!==-1){
      // 能找到 已经收藏过了  在数组中删除该商品
      collect.splice(index,1);
      isCollect=false;
      wx.showToast({
        title: '取消成功',
        icon: 'success',
        mask: true
      });
        
    }else{
      // 没有收藏过
      collect.push(this.GoodsInfo);
      isCollect=true;
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true
      });
    }
    // 4 把数组存入到缓存中
    wx.setStorageSync("collect", collect);
    // 5 修改data中的属性  isCollect
    this.setData({
      isCollect
    })
      
      
  }
})